<template>
  <el-dialog
    title="新增学科"
    :visible="showDialog"
    @close="closeDialogFn"
    top="20vh"
    width="30%">
    <!-- 表单 -->
    <el-form label-width="100px" :model="formData" :rules="rules" ref="addSubject">
      <el-form-item label="学科名称" prop="subjectName">
        <el-input
          v-model="formData.subjectName"
          style="width: 85%"
          placeholder="请输入学科名称"></el-input>
      </el-form-item>
      <el-form-item label="是否显示" prop="isFrontDisplay" required>
        <el-switch
          style="width: 85%"
          v-model="display"
          active-color="#13ce66">
        </el-switch>
      </el-form-item>
    </el-form>
    <!-- footer插槽 -->
    <template v-slot:footer>
      <el-button @click="closeDialogFn">取消</el-button>
      <el-button type="primary" @click="formAdd">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
// 导入封装的接口
import { add } from '@/api/hmmm/subjects'
export default {
  // 控制弹窗显示和隐藏
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      formData: {
        subjectName: '',
        isFrontDisplay: 1
      },
      display: true,
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 点击确定按钮
    formAdd () {
      this.$refs.addSubject.validate(async flag => {
        if (!flag) return
        this.formData.isFrontDisplay = this.display ? 1 : 0
        // 当flag不等于false时，将数据传入需要调用的接口
        console.log(this.display, this.formData.isFrontDisplay)
        await add(this.formData)
        this.$message.success('新增学科成功')
        this.closeDialogFn()
        // 重置数据需调用父组件方法
        this.$parent.subjectsList()
      })
    },
    // 关闭弹窗
    closeDialogFn () {
      // 直接改父组件的数据
      this.$parent.showDialog = false
      // 重置(绑定了校验的)数据
      this.$refs.addSubject.resetFields()
      this.display = true
    }
  },
  created () {

  }
}
</script>

<style scoped lang='less'></style>
